package com.yuguoxy.mytomcat;

import java.io.*;
import java.util.ArrayList;
//       POST  /home/user/login.html  HTTP/1.1
//    Host: 114.215.86.90
//    Cache-Control: no-cache
//    Postman-Token: bd243d6b-da03-902f-0a2c-8e9377f6f6ed
//    Content-Type: application/x-www-form-urlencoded
//
//       内容

/**
 * 读取客户端请求包内容，将流转为字符串并解析请求方法和url
 */
public class YGHttpRequest {
    private String method; //请求方法
    private String url;  //请求url
    private String content; //请求内容

    public YGHttpRequest(InputStream inputStream) throws IOException {
        //1. 解析请求行和请求头部
        // 读取请求行和请求头部
        StringBuilder requestLineAndHeader = new StringBuilder();
        String line = ""; //读取请求行内容
        String contentType = null;
        int contentLength = 0;
        do {
            line = readLine(inputStream, 0);
            if (line.startsWith("Content-Type")) {
                contentType = line.split(":")[1].trim();
                System.out.println("contentType : " + contentType);
            }
            if (line.startsWith("Content-Length")) {
                contentLength = Integer.parseInt(line.split(":")[1].trim());
                System.out.println("contentLength : " + contentLength);
            }
            requestLineAndHeader.append(line);
        } while (!line.equals("\r\n"));

        //2. 解析请求方法和url
        String headerContent = requestLineAndHeader.toString();
        System.out.println(headerContent);
        String[] requestStr = headerContent.split("\n");
        String requestLine = requestStr[0];
        String[] arrays = requestLine.split("\\s");
        String method = arrays[0];
        String url = arrays[1];
        this.method = method;
        this.url = url;

        if(contentLength != 0){
            //3. 解析请求正文内容
            if (contentType.startsWith("multipart/form-data")) {
                //写内容到临时文件
                writeTempFile(inputStream, contentLength);
            } else {
                if (this.method.equalsIgnoreCase("POST")) {
                    this.content = readLine(inputStream, contentLength);
                    System.out.println(content);
                }
            }
        }

    }

    /**
     * 读取请求头部和内容区块一行数据
     *
     * @param inputStream
     * @param contentLenght
     * @return
     * @throws IOException
     */
    private String readLine(InputStream inputStream, int contentLenght) throws IOException {
        ArrayList byteLists = new ArrayList();
        //读取头部区块行
        byte b;
        if (contentLenght == 0) {
            do {
                b = (byte) inputStream.read();
                byteLists.add(b);
            } while (b != 10); // \n
        } else {
            int count = 0;
            do {
                b = (byte) inputStream.read();
                byteLists.add(b);
                count++;
            } while (count < contentLenght);
        }

        int size = byteLists.size();
        byte[] tempBytes = new byte[size];
        for (int i = 0; i < size; i++) {
            tempBytes[i] = ((Byte) byteLists.get(i)).byteValue();
        }
        String str = new String(tempBytes, "utf-8");
        return str;

    }

    /**
     * 写请求正文到临时文件
     *
     * @param inputStream
     * @param contentLength
     * @throws IOException
     */
    private void writeTempFile(InputStream inputStream, int contentLength) throws IOException {
        String tempFile = "D:\\myupload\\tempfile";
        OutputStream os = new FileOutputStream(tempFile);
        byte[] b = new byte[contentLength];
        int n = inputStream.read(b);
        os.write(b, 0, n);
        os.close();
    }


    public String getMethod() {
        return method;
    }

    public String getUrl() {
        return url;
    }

    public String getContent() {
        return content;
    }
}
